#include "Image.h"
#include <iostream>
#include <fstream>

using namespace std;

void img::write_ppm(const char* filename, unsigned char* data, int w, int h) {

	 FILE* pFile;
	 char header[20];

	 pFile = fopen(filename, "wb");

	 // write "P6"
	 fwrite("P6\n", 3, 1, pFile);

	 // write "width height"
	 sprintf(header, "%d %d\n", w, h);
	 fwrite(header, strlen(header), 1, pFile);

	 // writeh "255"
	 fwrite("255\n", 4, 1, pFile);

	 // write rgb data
	 fwrite(data, w*h*3, 1, pFile);

	 fclose(pFile);
}

bool img::load_ppm(const char* filename, unsigned char* &data, int &w, int &h) {

    FILE* pFile = fopen(filename, "rb");
	if ( !pFile ) {   
        perror(filename);
		return false;
    }
	
	// grab first two chars of the file and make sure that it has the  
    // correct magic cookie for a raw PPM file.
	char head[70];          // max line = 70 in PPM (per spec).
    fgets(head, 70, pFile);
    if (strncmp(head, "P6", 2)) {
        cout<<filename<<": Not a raw PPM file\n"<<endl;
		return false;
    }

    // grab the three elements in the header (width, height, maxval).
	int d, i = 0;
    while(i < 3) {   
        fgets(head, 70, pFile);   
        if (head[0] == '#')     //skip comments.
            continue;   
        if (i == 0)   
            i += sscanf(head, "%d %d %d", &w, &h, &d);   
        else if (i == 1)   
            i += sscanf(head, "%d %d", &h, &d);   
        else if (i == 2)   
            i += sscanf(head, "%d", &d);   
    }

    // grab all the image data in one fell swoop.
    data = (unsigned char*)malloc( 3*w*h*sizeof(unsigned char) );
    fread(data, sizeof(unsigned char), 3*w*h, pFile);
    fclose(pFile);

	unsigned char temp;
	for( int v = 0; v < 0.5*h; ++v ) {
		for( int u = 0; u < 3*w; u += 3 ) {
			// v, h-1-v

			//r
			temp = data[v*3*w+u];
			data[v*3*w+u] = data[(h-1-v)*3*w+u];
			data[(h-1-v)*3*w+u] = temp;

			//g
			temp = data[v*3*w+u+1];
			data[v*3*w+u+1] = data[(h-1-v)*3*w+u+1];
			data[(h-1-v)*3*w+u+1] = temp;

			//b
			temp = data[v*3*w+u+2];
			data[v*3*w+u+2] = data[(h-1-v)*3*w+u+2];
			data[(h-1-v)*3*w+u+2] = temp;

		}
	}

	return true;

}